/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.unibo.as.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Johnny
 */
public class TableListPanel extends DialogBox{
   private final VerticalPanel vp;
   private final DialogBox newDialog;
   private GWTGameServiceAsync gameService;
   private AsyncCallback<ArrayList<Table>> updateTableListCallback;
   private CellTable<Table> cellTable;

    public TableListPanel() {
        
        gameService = GWT.create(GWTGameService.class);

        // MainView parent = (MainView)getParent();

        setText("Join/Create Table");

        vp = new VerticalPanel();
        vp.setWidth("600px");
        vp.setHeight("400px");
        setWidget(vp);
        
        cellTable = new CellTable<Table>();
        vp.add(cellTable);
        cellTable.setSize("600px", "400px");


        TextColumn<Table> nameColumn = new TextColumn<Table>(){
          @Override
          public String getValue(Table object) {
             return object.getName();
          }

        };
        
        TextColumn<Table> addressColumn = new TextColumn<Table>(){
        @Override
        public String getValue(Table object) {
           return  String.valueOf(object.getAIPlayers());
           }
        };

        TextColumn<Table> aiColumn = new TextColumn<Table>(){
        @Override
            public String getValue(Table object) {
                return  String.valueOf(object.getActivePlayers()) + "/4";
            }

        };

        // Add the columns.
        cellTable.addColumn(nameColumn, "Table ID");
        cellTable.addColumn(addressColumn, "Players");
        cellTable.addColumn(aiColumn, "AI Players");

        // Associate an async data provider to the table
        AsyncDataProvider<Table> provider = new AsyncDataProvider<Table>() {
            @Override
            protected void onRangeChanged(HasData<Table> display) {
                final int start = display.getVisibleRange().getStart();
                int length = display.getVisibleRange().getLength();
                updateTableListCallback = new AsyncCallback<ArrayList<Table>>() {
                @Override
                public void onFailure(Throwable caught) {
                    Window.alert(caught.getMessage());
                }
                @Override
                public void onSuccess(ArrayList<Table> result) {
                    updateRowData(start, result);
                }


                };

                gameService.fetchTablesPage(start, length, updateTableListCallback);
            }
        };

        provider.addDataDisplay(cellTable);




        Button joinBtn = new Button("Join Table");
        Button newBtn = new Button("New Table");
        Button cancelBtn = new Button("Cancel");
        Button refreshBtn = new Button("Refresh");

        HorizontalPanel tableBtns = new HorizontalPanel();
        tableBtns.add(joinBtn);
        tableBtns.add(newBtn);
        tableBtns.add(refreshBtn);
        tableBtns.add(cancelBtn);

        
        /* create New Game dialog box */
        
        newDialog = new DialogBox();
        newDialog.setText("New Table");

        FlexTable newLayout = new FlexTable();
        
        newLayout.setCellSpacing(6);

        final TextBox fnameBox = new TextBox();
        newLayout.setHTML(0, 0, "Table name: ");
        newLayout.setWidget(0, 1, fnameBox);

        
        newLayout.setHTML(1, 0, "AI Players: ");
        final ListBox aiBox = new ListBox();
        aiBox.addItem("0");
        aiBox.addItem("1");
        aiBox.addItem("2");
        aiBox.addItem("3");
        aiBox.setVisibleItemCount(4);
        newLayout.setWidget(1, 1, aiBox);

        newLayout.setHTML(2, 0, "Match: ");
        ListBox matchBox = new ListBox();
        matchBox.addItem("Single Deal");
        matchBox.addItem("Four Deals");
        matchBox.setVisibleItemCount(2);
        newLayout.setWidget(2, 1, matchBox);

        Button createBtn = new Button("Create Table");
        newLayout.setWidget(4,0, createBtn);

        Button newCancelBtn = new Button("Cancel");
        newLayout.setWidget(4,1, newCancelBtn);

        newDialog.setWidget(newLayout);

        /* set Button Click events */

        newBtn.addClickHandler(new ClickHandler(){
        @Override
            public void onClick(ClickEvent event) {
                newDialog.center();
                newDialog.show();
                newDialog.getElement().getStyle().setZIndex(155);
            }
        });

        refreshBtn.addClickHandler(new ClickHandler(){
        @Override
            public void onClick(ClickEvent event) {
                updateListTable();
            }
        });

        cancelBtn.addClickHandler(new ClickHandler(){
        @Override
            public void onClick(ClickEvent event) {
                hide();
            }
        });

        /* set New Table Dialog buttons click events */

        newCancelBtn.addClickHandler(new ClickHandler(){
        @Override
            public void onClick(ClickEvent event) {
                newDialog.hide();
            }
        });

        createBtn.addClickHandler(new ClickHandler(){
             final AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
                @Override
                public void onSuccess(Boolean result) {
                    if(result){
                        newDialog.hide();
                        updateListTable();
                    }
                    else{
                        /* On failure, set error label */
                        newDialog.setText("New Table -- Error");

                    }

                }

                @Override
                public void onFailure(Throwable caught) {
                    setText("Join/Create Table -- Error");
                }
            };

        @Override
            public void onClick(ClickEvent event) {
                gameService.createTable(fnameBox.getText(), Boolean.FALSE, aiBox.getSelectedIndex(), callback);
            }
        });

        /* add buttons row */

        vp.add(tableBtns);

        /* if there is no active table for the currente user, disable cancelBtn */

        //TODO cancelBtn.setEnabled(false);

        getElement().getStyle().setZIndex(150);

    }

    void updateListTable(){
        int start = cellTable.getVisibleRange().getStart();
        int length = cellTable.getVisibleRange().getLength();
        gameService.fetchTablesPage(start, length, updateTableListCallback);

    }

}
